<template>
  <input
    type="range"
    class="slider"
    ref="sliderEl"
    @input="input"
    @change="change"
    :value="modelValue"
    :min="min"
    :max="max"
    :style="{ backgroundSize: `${leftSize}% 100%` }"
  />
</template>

<script setup lang="ts">
interface Props {
  modelValue: number
  min?: number
  max?: number
}

const props = withDefaults(defineProps<Props>(), {
  min: 0,
  max: 100
})

const emit = defineEmits(['update:modelValue', 'input', 'change'])

const sliderEl = ref()
const leftSize = ref(100)

const calcSlider = () => {
  const slider = sliderEl.value
  leftSize.value = ((slider.value - props.min) / (props.max - props.min)) * 100
}

onMounted(calcSlider)

const input = (e: any) => {
  calcSlider()
  emit('update:modelValue', +e.target.value)
  emit('input', props.modelValue)
}
const change = (e: any) => {
  calcSlider()
  emit('update:modelValue', +e.target.value)
  emit('change', props.modelValue)
}
</script>

<style scoped lang="scss">
.slider {
  appearance: none;
  width: 200px;
  height: 8px;
  background: linear-gradient($main-color, $main-color) no-repeat #fff;
  border-radius: 4px;
  cursor: pointer;

  &::-ms-thumb {
    background: $main-color;
  }

  &::-moz-range-thumb {
    background: $main-color;
  }

  &::-webkit-slider-thumb {
    appearance: none;
    background: $main-color;
    height: 15px;
    width: 15px;
    border-radius: 50%;
    transition: 0.4s;

    &:hover {
      transform: scale(1.2);
    }
  }
}
</style>
